import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import { useTodosStore } from './todos'
import { getStorageSync, setStorageSync } from '../utils/storage'

export const useFilterTodosStore = defineStore('filterTodos', () => {
  const todosStore = useTodosStore()
  
  // 非默认的过滤项 (即用户主动选择的过滤项)
  const selectedOption = computed(() => {
    const { status, labels, timeRange, keyword } = filterOptions.value
    const options: FilterOptionKey[] = []

    if (status !== 'all') {
      options.push('status')
    }
    if (labels.length > 0) {
      options.push('labels')
    }
    if (timeRange) {
      options.push('timeRange')
    }
    if (keyword) {
      options.push('keyword')
    }

    return options
  })

  // 筛选选项
  const filterOptions = ref<FilterOptions>({
    status: 'all',
    labels: [],
    timeRange: null,
    keyword: ''
  })
  
  // 设置筛选选项
  const setFilterOptions = (options: Partial<FilterOptions>) => {
    filterOptions.value = { ...filterOptions.value, ...options }
    // console.log('setFilterOptions', filterOptions.value)
  }
  
  // 重置筛选选项
  const resetFilterOptions = () => {
    filterOptions.value = {
      status: 'all',
      labels: [],
      timeRange: null,
      keyword: ''
    }
  }
  
  // 筛选后的待办事项列表
  const filteredTodos = computed(() => {
    return todosStore.todoList
      .filter(todo => {
        // 状态筛选
        if (filterOptions.value.status !== 'all' && todo.status !== filterOptions.value.status) {
          return false
        }
        
        // 标签筛选
        if (filterOptions.value.labels && filterOptions.value.labels.length > 0) {
          const hasMatchingLabel = filterOptions.value.labels.some(label => 
            todo.labels.some(todoLabel => todoLabel.name === label.name)
          )
          if (!hasMatchingLabel) {
            return false
          }
        }
        
        // 时间范围筛选
        if (filterOptions.value.timeRange && filterOptions.value.timeRange.length === 2) {
          const [startDate, endDate] = filterOptions.value.timeRange
          if (todo.time) {
            const todoDate = new Date(todo.time).getTime()
            const startTime = new Date(startDate).getTime()
            const endTime = new Date(endDate).getTime()
            
            if (todoDate < startTime || todoDate > endTime) {
              return false
            }
          } else {
            // 如果待办事项没有时间，也包含在筛选结果中
            return true
          }
        }
        
        // 关键词搜索
        if (filterOptions.value.keyword && filterOptions.value.keyword.trim() !== '') {
          const keyword = filterOptions.value.keyword.trim().toLowerCase()
          const titleMatch = todo.title.toLowerCase().includes(keyword)
          const remarkMatch = todo.remark.toLowerCase().includes(keyword)
          const descriptionMatch = todo.description.toLowerCase().includes(keyword)
          const locationMatch = todo.location.toLowerCase().includes(keyword)
          
          if (!titleMatch && !remarkMatch && !descriptionMatch && !locationMatch) {
            return false
          }
        }
        
        return true
      })
  })

  // 切换批量管理Todo的选中状态
  const toggleSelectedTodo = (todo: Todo) => {
    const index = todosStore.todoList.findIndex(item => item.id === todo.id)
    if (index !== -1) {
      todosStore.todoList[index].isSelected = !todosStore.todoList[index].isSelected
    }
  }

  // 是否全选了所有待办事项
  const isSelectedAll = computed(() => {
    const selectedTodosLength = todosStore.todoList.reduce((acc, todo) => {
      return todo.isSelected ? acc + 1 : acc
    }, 0)
    
    return selectedTodosLength >= filteredTodos.value.length
  })

  // 全选所有待办事项或全不选
  const selectAllTodos = (clear = false) => {
    if (clear || isSelectedAll.value) {
      todosStore.todoList.forEach(todo => {
        todo.isSelected = false
      })
    } else {
      todosStore.todoList.forEach(todo => {
        todo.isSelected = true
      })
    }
  }

  const getFilterOptions = () => {
    try {
      const res: FilterOptions | null = getStorageSync('filterOptions')
      if (res) {
        filterOptions.value = res
      }
    } catch (error) {
      console.log(error)
    }
  }

  const saveFilterOptions = () => {
    try {
      setStorageSync<FilterOptions>('filterOptions', filterOptions.value)
    } catch (error) {
      console.log(error)
    }
  }

  watch(() => filterOptions.value, saveFilterOptions)
  
  return {
    filterOptions,
    selectedOption,
    setFilterOptions,
    resetFilterOptions,
    filteredTodos,
    getFilterOptions,
    toggleSelectedTodo,
    isSelectedAll,
    selectAllTodos
  }
})